package cn.blunce.utils.network;

import android.annotation.SuppressLint;
import android.os.Handler;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * http协议，用json上传和下载数据
 * <p/>
 * Created by Blunce on 2015/11/23 0023.
 */
public class HttpHelper {

    private static String[] urls = {
            "http://.....",
            "http://..."
    };

    private static String token = "";


    public static void httpconnect(final Handler handler, final int url_index, final String args) {
        new Thread() {
            @Override
            public void run() {
                try {
                    httpConnection(handler, url_index, args);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public static void httpConnection(final Handler handler, final int url_index, final String args) throws Exception {
        HttpURLConnection connection = null;
        URL url = new URL(urls[url_index]);
        if (url.getProtocol().equalsIgnoreCase("https")) {
            trustAllHosts();
            HttpsURLConnection
                    .setDefaultHostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname,
                                              SSLSession session) {
                            return true;
                        }
                    });
            HttpsURLConnection https = (HttpsURLConnection) url
                    .openConnection();
            connection = https;
        } else {
            connection = (HttpURLConnection) url.openConnection();
        }

        if (args != null) {
            connection.setDoInput(true);
            connection.setDoOutput(true); // 发送POST请求必须设置允许输出
            connection.setUseCaches(false); // 不使用Cache
            connection.setRequestMethod("POST");
            connection.setReadTimeout(5000);
            connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            // conn.setRequestProperty("Content-Length", "0");
            connection.setRequestProperty("Content-Type",
                    "application/json;charset=utf-8");
            connection.setRequestProperty("toekn", token);
            OutputStream outs = connection.getOutputStream();
            outs.write(args.getBytes());
        } else {
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
        }

        int state = 0;
        state = connection.getResponseCode();

        if (state == 200) {
            //判断成功
            String data = GetResponseString(connection);
        }
    }

    @SuppressLint("TrulyRandom")
    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        // Android 采用X509的证书信息机制
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
        }};
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static private String GetResponseString(HttpURLConnection huc)
            throws Exception {
        InputStream re = huc.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(re));
        StringBuffer buffer = new StringBuffer();
        String line = new String();
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
        String responseString = buffer.toString();
        return responseString;
    }
}
